import { reactive, ref } from 'vue'
import { cities, provinces } from './city.data'

export function useCityPicker() {
	const pickerRef = ref<any>(null)
	const columns = reactive([
		provinces,
		cities[0],
	])
	const show = ref(false)

	const onChange = (e: any) => {
		if (e.columnIndex === 0) {
			pickerRef.value.setColumnValues(1, cities[e.index])
		}
	}

	const open = (value: string) => {
		let pIndex = 0
		let cIndex = 0

		if (value) {
			const [pv, cv] = value.split('-')

			if (pv) {
				pIndex = provinces.findIndex((item) => item.label === pv)
				pIndex = Math.max(0, pIndex)
			}
			if (cv) {
				cIndex = cities[pIndex].findIndex((item) => item.label === cv)
				cIndex = Math.max(0, cIndex)
			}
		}

		pickerRef.value.setColumnValues(1, cities[pIndex])
		pickerRef.value.setIndexs([pIndex, cIndex])

		show.value = true
	}

	const close = () => {
		show.value = false
	}

	return {
		pickerRef,
		columns,
		show,
		onChange,
		open,
		close,
	}
}
